package com.yonyou.gmmc.service.points.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.marketing.common.dto.MessageDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MapConverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.points.constant.PointsConstant;
import com.yonyou.gmmc.service.points.dao.TmCouponInfoMapper;
import com.yonyou.gmmc.service.points.dao.TmCouponMapper;
import com.yonyou.gmmc.service.points.model.TmCoupon;
import com.yonyou.gmmc.service.points.model.TmCouponInfo;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
@Transactional
public class TicketService{

    private static Logger      logger = LoggerFactory.getLogger(TicketService.class);
    @Autowired
    private TmCouponMapper     tmCouponMapper;
    @Autowired
    private TmCouponInfoMapper tmCouponInfoMapper;

    @Autowired
    private BaseService              eventService;

    public Map<String,Object> checkFans(String userId) {
        Map<String,Object> result = new HashMap<>();
        try{
            logger.info("用户的OPEN_ID为>>>>"+userId);
            Integer count = tmCouponInfoMapper.checkFans(Integer.valueOf(userId));
            if(count==1){
                logger.info("该用户不是粉丝");
                result.put("flag", "0");
                result.put("msg", "可以查看卡包！");
            }else{
                logger.info("用户是粉丝");
                result.put("flag", "1");
                result.put("msg", "请先注册成为会员！");
            }
        }catch(Exception e){
            logger.error(e.getMessage());
            result.put("flag", "2");
            result.put("msg", "进入异常，请重试！");
        }
        return result;
    }
    
    public PageInfo<Map<String, Object>> getTicketList(Map<String, Object> map) {
    	logger.info("进入Service方法：getTicketList");
        logger.info("TicketService.getTicketList==>pro:" + map.get("pro"));
        // 原来的0 未使用 1 已使用 2已过期和已取消 前端传过来的
        // 10050000 未发放 10050001 未使用 10050002 已使用 10050003 已取消 对应后台的状态
        String status = map.get("status").toString();
        Integer userId = Integer.valueOf(map.get("userId").toString());
        // 查询优惠券
        logger.info("查询优惠券分页");
        Page<Map<String, Object>> ss = PageHelper.startPage(Integer.parseInt(map.get("pageNum").toString()),
                                                            Integer.parseInt(map.get("pageSize").toString()));
        logger.info("ss为————" + ss);
        List<Map<String, Object>> list = tmCouponMapper.queryCouponList(userId,status);

        PageInfo<Map<String, Object>> page = new PageInfo<>(list);
        logger.info("page为————" + page);
        return page;
    }

    @SuppressWarnings("unchecked")
    public List<Long> bindTicket(Map<String, Object> map) throws Exception {
        Integer userId = Integer.valueOf(map.get("userId").toString());
        String dealerCode = map.get("dealerCode").toString();
        String bizId = map.get("bizId").toString();
        String tcName = tmCouponInfoMapper.selectTcName(map.get("triggerCode").toString());
        // 若不传经销商Code 默认为厂商
        if (CheckUtil.NullOrEmpty(map.get("dealerCode")) || "".equals(map.get("dealerCode"))) {
            dealerCode = "00000";
        }
        Long serialNo = 0l;
        List<Long> arrayList = new ArrayList<>();
        // Example example = new Example(TmCouponInfo.class);
        // Criteria criteria = example.createCriteria();
        // criteria.andEqualTo("bcId", map.get("bizCode"));
        // criteria.andEqualTo("tcId", map.get("triggerCode"));
        // criteria.andEqualTo("dealerCode", "00000");
        // if(CheckUtil.NullOrEmpty(map.get("batchId")) && !"".equals(map.get("batchId").toString())
        // &&PointsConstant.BIZ_CASE_1999.equals(map.get("batchId").toString())){
        // criteria.andEqualTo("batchId", map.get("batchId"));
        // }
        // criteria.andCondition("TO_CHAR(VALID_DATE_END,'YYYY-MM-DD') >= ", "TO_CHAR(SYSDATE,'YYYY-MM-DD')");
        // example.setOrderByClause("BATCH_ID ASC");
        // List<TmCouponInfo> couponInfo = tmCouponInfoMapper.selectByExample(example);
        List<TmCouponInfo> couponInfo = tmCouponInfoMapper.selectCoupon(map.get("bizCode").toString(),
                                                                        map.get("triggerCode").toString(), "00000",
                                                                        map.get("batchId").toString());
        // 查询可用优惠券
        if (!CheckUtil.NullOrEmpty(couponInfo) && !couponInfo.isEmpty()) {
            TmCouponInfo ticketsBatch = couponInfo.get(0);
            String batchId = ticketsBatch.getBatchId();
            map.put("batch_id", batchId);
            if (checkCoupon(map)) {
                Map<String, Object> takeCoupon = takeCoupon(userId, batchId, 1, bizId);
                logger.info("绑定优惠券1");
                Integer bindingResult = (Integer) takeCoupon.get("bindingResult");
                if (bindingResult == 1) {
                    List<Map<String, Object>> tickets = (List<Map<String, Object>>) takeCoupon.get("couponList");
                    Map<String, Object> co = tickets.get(0);
                    serialNo = Long.valueOf(co.get("couponId").toString());
                    arrayList.add(serialNo);
                    logger.info("发送消息通知");
                    MessageDto dto = new MessageDto();
                    dto.setMessageContent("您有一张优惠券已到账，券号{"+serialNo+"}，获取原因{"+tcName+"}，请至个人中心-我的卡包查收并使用！");
                    dto.setMessageTitle("优惠券发放");
                    dto.setMessageType("40011005");
                    dto.setUserId(userId.longValue());
                    BizEvent et = new BizEvent();
                    et.setEventBizType(EventBizType.SEND_MESSAGE);
                    et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
                    et.setEventKey("MESSAGE:" + dto.getUserId() + ":" + new Date().getTime());
                    et.setEventData(MapConverUtil.PO2Map(dto));
                    String s = eventService.sendEvent2MQ(et);
                    logger.info("发送消息通知，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
                } else {
                    updateCouponInfo(batchId);
                }
            }
        }

        // 领取销售店优惠券
        if (!"00000".equals(dealerCode)) {
            // Example exa = new Example(TmCouponInfo.class);
            // Criteria cri = exa.createCriteria();
            // cri.andEqualTo("bcId", map.get("bizCode"));
            // cri.andEqualTo("tcId", map.get("triggerCode"));
            // cri.andEqualTo("dealerCode", dealerCode);
            // if(CheckUtil.NullOrEmpty(map.get("batchId")) && !"".equals(map.get("batchId").toString())
            // &&PointsConstant.BIZ_CASE_1999.equals(map.get("batchId").toString())){
            // cri.andEqualTo("batchId", map.get("batchId"));
            // }
            // cri.andCondition("TO_CHAR(VALID_DATE_END,'YYYY-MM-DD') >= ", "TO_CHAR(SYSDATE,'YYYY-MM-DD')");
            // exa.setOrderByClause("BATCH_ID ASC");
            // List<TmCouponInfo> ticketsBatch = tmCouponInfoMapper.selectByExample(exa);
            List<TmCouponInfo> ticketsBatch = tmCouponInfoMapper.selectCoupon(map.get("bizCode").toString(),
                                                                              map.get("triggerCode").toString(),
                                                                              dealerCode,
                                                                              map.get("batchId").toString());
            // 查询可用优惠券
            if (!CheckUtil.NullOrEmpty(ticketsBatch) && !ticketsBatch.isEmpty()) {
                TmCouponInfo info = ticketsBatch.get(0);
                String batchId = info.getBatchId();
                map.put("batch_id", batchId);
                // if (checkCoupon(map)) {
                Map<String, Object> takeCoupon = takeCoupon(userId, batchId, 1, bizId);
                logger.info("绑定优惠券2");
                Integer bindingResult = (Integer) takeCoupon.get("bindingResult");
                if (bindingResult == 1) {
                    List<Map<String, Object>> tickets = (List<Map<String, Object>>) takeCoupon.get("couponList");
                    Map<String, Object> co = tickets.get(0);
                    serialNo = Long.valueOf(co.get("couponId").toString());
                    arrayList.add(serialNo);
                    logger.info("发送消息通知");
                    MessageDto dto = new MessageDto();
                    dto.setMessageContent("您有一张优惠券已到账，券号{"+serialNo+"}，获取原因{"+tcName+"}，请至个人中心-我的卡包查收并使用！");
                    dto.setMessageTitle("优惠券发放");
                    dto.setMessageType("40011005");
                    dto.setUserId(userId.longValue());
                    BizEvent et = new BizEvent();
                    et.setEventBizType(EventBizType.SEND_MESSAGE);
                    et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
                    et.setEventKey("MESSAGE:" + dto.getUserId() + ":" + new Date().getTime());
                    et.setEventData(MapConverUtil.PO2Map(dto));
                    String s = eventService.sendEvent2MQ(et);
                    logger.info("发送消息通知，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
                } else {
                    updateCouponInfo(batchId);
                }
                // }

            }
        }
        return arrayList;
    }

    /**
     * <p>
     * Description: 限制业务场景中优惠券的数量
     * </p>
     * 
     * @param bizCode
     * @param triggerCode
     * @param userId
     * @param dealerCode
     */
    private boolean checkCoupon(Map<String, Object> map) {
        // 查询注册用户同一场景、同一触发、同一批次优惠券的数量
        Integer num = tmCouponMapper.queryCouponNum(map);
        logger.info("查询出的结果为："+num);
        if (num >= 1) {
        	logger.info("不能再次发券");
            return false;
        } else {
        	logger.info("可以发券");
            return true;
        }
    }

    public Map<String, Object> takeCoupon(Integer userId, String batchId, Integer total,
                                          String bizId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<Map<String, Object>> select = tmCouponMapper.getCoupon(batchId);
        Map<String, Object> map;
        if (!CheckUtil.NullOrEmpty(select) && select.size() >= total) {
            logger.debug("========================>> size= " + select.size());
            List<Map<String, Object>> arrayList = new ArrayList<>();
            for (int i = 0; i < total; i++) {
                map = select.get(i);
                logger.debug("========================>> map= " + map);
                Map<String, Object> coupon = new HashMap<>();
                coupon.put("couponId", map.get("COUPON_ID"));
                coupon.put("couponBegin", DateUtil.formateDate((Date) map.get("COUPON_BEGIN"), "yyyy-MM-dd"));
                coupon.put("couponEnd", DateUtil.formateDate((Date) map.get("COUPON_END"), "yyyy-MM-dd"));
                Integer couponType = Integer.valueOf(map.get("TICKET_TYPE").toString());
                coupon.put("couponType", couponType);
                if (couponType == 10080001) {
                    coupon.put("couponContent", map.get("COST"));
                } else if (couponType == 10080002 || couponType == 10080003) {
                    coupon.put("couponContent", map.get("DISCOUNT"));
                } else if (couponType == 10080004) {
                    coupon.put("couponContent", map.get("EXCHANGE_METHOD"));
                }
                logger.info("正式发放 更新数据库");
                Example example = new Example(TmCoupon.class);
                Criteria criteria = example.createCriteria();
                criteria.andEqualTo("couponId", map.get("COUPON_ID"));
                TmCoupon record = new TmCoupon();
                record.setUserId(userId);
                record.setCouponStatus(10050001);
                record.setUpdateDate(new Date());
                record.setPublishDate(new Date());
                record.setBizId(bizId);
                tmCouponMapper.updateByExampleSelective(record, example);
                if (select.size() == total) {
                    updateCouponInfo(batchId);
                }
                arrayList.add(coupon);
            }

            hashMap.put("couponList", arrayList);
            hashMap.put("bindingResult", 1);
        } else {
            logger.info("==================>> selectOneRow is null or empty.");
            hashMap.put("errorContent", "优惠券数量不足");
            hashMap.put("bindingResult", 0);
        }
        logger.info("========================>> Out take Coupon ,bindingResult{serialNo=" + hashMap + "}");
        return hashMap;
    }

    /**
     * <p>
     * Description: 更新优惠券批次状态0（优惠券已发完）
     * 
     * @param batchId
     */
    private void updateCouponInfo(String batchId) {
        Example ex = new Example(TmCouponInfo.class);
        Criteria cr = ex.createCriteria();
        cr.andEqualTo("batchId", batchId);
        TmCouponInfo info = new TmCouponInfo();
        info.setStatus(10060002);
        info.setUpdateDate(new Date());
        info.setUpdateBy(PointsConstant.OPT_USER);
        tmCouponInfoMapper.updateByExampleSelective(info, ex);
    }
    
    
    @SuppressWarnings("unchecked")
	public List<Long> bindNewUserTicket() throws Exception {
    	Example example = new Example(TmCouponInfo.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("grantType", 1);
        criteria.andEqualTo("status", 10060001);
        String date = DateUtil.formateDate(new Date(), "yyyy-MM-dd");
        criteria.andCondition("to_char(valid_date_end,'yyyy-MM-dd') >= ", date);

        List<TmCouponInfo> couponInfo = tmCouponInfoMapper.selectByExample(example);
        
        Long serialNo = 0l;
        List<Long> arrayList = new ArrayList<>();
        // 查询可用优惠券
        if (!CheckUtil.NullOrEmpty(couponInfo) && !couponInfo.isEmpty()) {
        	for (TmCouponInfo info : couponInfo) {
        		Map<String,Object> map = MapConverUtil.PO2Map(info);
        		List<String> couMo = tmCouponInfoMapper.queryCouponInfoModel(info.getBatchId(), 0);
        		String cName = "";
        		if (!CheckUtil.NullOrEmpty(couMo)&&!couMo.isEmpty()) {
                    for (String str : couMo) {
                        cName += "'"+str+"',";
                    }
                    if(!CheckUtil.NullOrEmpty(cName)){
                        cName = cName.substring(0, cName.length()-1);
                    }
                }
        		map.put("CITY", cName);
        		List<String> couMo1 = tmCouponInfoMapper.queryCouponInfoModel(info.getBatchId(), 1);
        		String bdealer = "";
        		if (!CheckUtil.NullOrEmpty(couMo1)&&!couMo1.isEmpty()) {
                    for (String str : couMo1) {
                    	bdealer += "'"+str+"',";
                    }
                    if(!CheckUtil.NullOrEmpty(bdealer)){
                    	bdealer = bdealer.substring(0, bdealer.length()-1);
                    }
                }
        		map.put("BDEALER", bdealer);
        		List<String> couMo2 = tmCouponInfoMapper.queryCouponInfoModel(info.getBatchId(), 2);
        		String sdealer = "";
        		if (!CheckUtil.NullOrEmpty(couMo2)&&!couMo2.isEmpty()) {
                    for (String str : couMo2) {
                    	sdealer += "'"+str+"',";
                    }
                    if(!CheckUtil.NullOrEmpty(sdealer)){
                    	sdealer = sdealer.substring(0, sdealer.length()-1);
                    }
                }
        		map.put("SDEALER", sdealer);
        		List<Integer> list = new ArrayList<>();
        		logger.info("筛选人数参数==========>> map= " + map);
        		list = tmCouponInfoMapper.findUserList(map);
        		for (Integer userId : list) {
        			Map<String, Object> takeCoupon = takeCoupon(userId, info.getBatchId(), 1, "");
                    logger.info("定时--------绑定优惠券");
                    Integer bindingResult = (Integer) takeCoupon.get("bindingResult");
                    if (bindingResult == 1) {
                    	boolean f = Boolean.getBoolean(info.getPushflg());
                    	if(f){
                    		List<Map<String, Object>> tickets = (List<Map<String, Object>>) takeCoupon.get("couponList");
                            Map<String, Object> co = tickets.get(0);
                            serialNo = Long.valueOf(co.get("couponId").toString());
                            arrayList.add(serialNo);
                            logger.info("发送消息通知");
                            MessageDto dto = new MessageDto();
                            dto.setMessageContent(info.getPushMsg());
                            dto.setMessageTitle("优惠券发放");
                            dto.setMessageType("40011005");
                            dto.setUserId(userId.longValue());
                            BizEvent et = new BizEvent();
                            et.setEventBizType(EventBizType.SEND_MESSAGE);
                            et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
                            et.setEventKey("MESSAGE:" + dto.getUserId() + ":" + new Date().getTime());
                            et.setEventData(MapConverUtil.PO2Map(dto));
                            String s = eventService.sendEvent2MQ(et);
                            logger.info("发送消息通知，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
                    	}
                    } else {
                        updateCouponInfo(info.getBatchId());
                        break;
                    }
				}
			}
        }

        return arrayList;
    }
}
